package jenkins

import (
	"gorm.io/gorm"
	"project-info/src/constants"
	"project-info/src/handle/response"
	"project-info/src/lib"
	"project-info/src/model"
	routeReq "project-info/src/router/req"
	"time"
)

// AddItem 添加项目
func AddItem(c *lib.GinContext) error {
	var item *model.Item
	if err := c.Bind(&item); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var count int64
	db := model.DB().Where("app_name = ?", item.AppName)
	db.Count(&count)
	if count > 1 {
		return response.JsonFail(c, "AppName名称已存在")
	} else if count == 1 {
		var appNameAndIdCount int64
		db.Where("id = ?", item.Id).Count(&appNameAndIdCount)
		if appNameAndIdCount == 0 {
			return response.JsonFail(c, "AppName名称已存在")
		}
	}

	item.Time = time.Now()
	if item.Id != 0 {
		model.DB().Save(item)
	} else {
		token := lib.JwtParse(c)
		model.DB().Transaction(func(tx *gorm.DB) error {
			err := tx.Create(item).Error
			if err != nil {
				return err
			}
			return tx.Create(&model.ResourceUser{
				ResourceId:   uint64(item.Id),
				ResourceType: constants.Item,
				UserId:       token.UserId,
			}).Error
		})
	}

	return response.JsonOk(c, item, "success")
}

// GetItemManageTree 获取项目树
func GetItemManageTree(c *lib.GinContext) error {
	var items []*model.Item
	err := model.DB().Find(&items).Error
	if err != nil {
		return err
	}

	tree := make([]*model.Item, 0)
	configMap := make(map[uint]*model.Item)
	for _, config := range items {
		configMap[config.Id] = config
	}

	for i, config := range items {
		parentID := items[i].ParentID
		if parentID == 0 {
			tree = append(tree, config)
		} else {
			parent, ok := configMap[parentID]
			if ok {
				parent.Children = append(parent.Children, config)
			}
		}
	}

	return response.JsonOk(c, tree, "success")
}

// GetItemTreeWithPermission 获取项目树
func GetItemTreeWithPermission(c *lib.GinContext) error {
	db := model.DB()
	db, err := routeReq.HandleResourceDataPermission(c, []int8{constants.Item}, db)
	if err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "数据权限校验出错")
	}

	var items []*model.Item
	err = db.Find(&items).Error
	if err != nil {
		return err
	}

	tree := make([]*model.Item, 0)
	configMap := make(map[uint]*model.Item)
	for _, config := range items {
		configMap[config.Id] = config
	}

	for i, config := range items {
		parentID := items[i].ParentID
		if parentID == 0 {
			tree = append(tree, config)
		} else {
			parent, ok := configMap[parentID]
			if ok {
				parent.Children = append(parent.Children, config)
			}
		}
	}

	return response.JsonOk(c, tree, "success")
}

// DelItem 删除项目
func DelItem(c *lib.GinContext) error {
	var item *model.Item
	if err := c.Bind(&item); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	model.DB().Where("id = ?", item.Id).Delete(&model.Item{})
	return response.JsonOk(c, item, "success")
}
